<template>
  <div class="content">
    <div class="content-table">
      <div class="content-table--wrap">
        <div class="table-left">
          <div>待选人员:</div>
          <el-row class="table-left--header">
            <el-col :span="18"
              ><el-input
                clearable
                placeholder="输入姓名查询"
                v-model="formInline.nameLike"
              ></el-input
            ></el-col>
            <el-col :span="6"
              ><el-button
                class="table-left--btn"
                type="primary"
                @click="handleSearch"
                >查询</el-button
              ></el-col
            >
          </el-row>
          <el-table
            key="table-left"
            @selection-change="handleSelectionChange"
            ref="multipleTable"
            :data="userList"
            border
            style="width: 380px"
            :height="300"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            :row-key="getRowKeys"
          >
            <template #empty>
              <el-empty :image-size="150" description="暂无数据"></el-empty>
            </template>
            <el-table-column
              type="selection"
              :reserve-selection="true"
              width="50"
            />
            <el-table-column
              prop="name"
              label="姓名"
              width="60"
            ></el-table-column>
            <el-table-column
              prop="userName"
              label="用户名"
              show-overflow-tooltip
            ></el-table-column>
          </el-table>
          <div class="table-left--footer">
            <re-pagination
              :layout="`total, prev, pager, next`"
              :total="total"
              v-model:page="formInline.pageNum"
              v-model:limit="formInline.pageSize"
              @pagination="handleSearch"
            />
          </div>
        </div>
        <div class="table-right">
          <div>已选人员:</div>
          <div class="table-right--header"></div>
          <el-table
            key="table-right"
            :data="multipleSelection"
            border
            style="width: 380px"
            :height="300"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          >
            <template #empty>
              <el-empty :image-size="150" description="暂无数据"></el-empty>
            </template>
            <el-table-column
              type="index"
              label="序号"
              width="50"
            ></el-table-column>
            <el-table-column
              prop="name"
              label="姓名"
              width="60"
            ></el-table-column>
            <el-table-column
              prop="userName"
              label="用户名"
              show-overflow-tooltip
            ></el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
  <div class="form__footer">
    <el-button @click="handleCancel">取 消</el-button>
    <el-button type="primary" @click="handleSubmit">确 定</el-button>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineEmits, defineProps, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import { postChangeAssignee } from "/@/api/acceptance";
import { getUserList } from "/@/api/user";
import NotifMessage from "/@/utils/message/notification";

const emit = defineEmits(["update:dialogVisibleTransfer"]);
const props = defineProps({
  taskId: {
    type: String,
    default: ""
  }
});

const router = useRouter();
const route = useRoute();

// -----------------------------------
import RePagination from "/@/components/RePagination/index.vue";

let userList = ref([]);
let multipleSelection = ref([]);
let total = ref(0);
let formInline = reactive({
  nameLike: "",
  pageNum: 1,
  pageSize: 50
});
const multipleTable = ref<HTMLElement | null>(null) as any;

const getRowKeys = row => {
  return row.id;
};

const handleSearch = () => {
  getUserLists(formInline);
};

const getUserLists = async (obj: object = {}) => {
  try {
    const { code, data } = await getUserList(obj);
    if (code === 200) {
      total.value = data.rows;
      userList.value = data.list.map(item => {
        return {
          id: item.id,
          name: item.name,
          userName: item.userName
        };
      });
    }
  } catch (err) {
    console.log(err);
  } finally {
    multipleTable.value.doLayout();
  }
};

const handleSelectionChange = selection => {
  // console.log(selection, "selection");
  multipleSelection.value = [];
  if (selection.length > 1) {
    let del_row = selection.shift();
    // console.log('把数组的第一个元素从其中删除后', selection);
    multipleTable.value.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
  }
  multipleSelection.value.push(selection[0]);
  let obj = {};
  multipleSelection.value = multipleSelection.value.reduce(function (
    item,
    next
  ) {
    obj[next.id] ? "" : (obj[next.id] = true && item.push(next));
    return item;
  },
  []);
};

getUserLists({
  pageNum: 1,
  pageSize: 50,
  nameLike: ""
});

// const toggleSelection = rows => {
//   if (rows) {
//     rows.forEach(row => {
//       multipleTable.value.toggleRowSelection(row);
//     });
//   } else {
//     multipleTable.value.clearSelection();
//   }
// };
// -----------------------------------

const handleSubmit = async () => {
  const { instanceId, contractId } = route.query;
  if (multipleSelection.value.length !== 1) {
    NotifMessage.error("只能选择一个人员进行转办");
    return;
  }
  const params = {
    targetAssignee: multipleSelection.value[0].id,
    opinion: "转办：转办协助处理!",
    instanceId,
    taskId: props.taskId,
    businessTraParam: {
      id: contractId,
      acceptUsers: multipleSelection.value[0].id,
      flowType: 1
    }
  };
  try {
    const { code, message } = await postChangeAssignee(params);
    if (code === 200) {
      NotifMessage.success("转办成功");
      handleCancel();
      // router.replace("/acceptance/arrival");
      handleBack();
    } else {
      NotifMessage.error(message || "请求出错");
    }
  } catch (err) {
    console.log(err);
  }
};

const handleBack = () => {
  // TODO  根据来源进行处理
  if (route.query.source === "work") {
    router.push({ path: "/work/dashboard", replace: true });
  } else {
    router.push({ path: "/acceptance/arrival", replace: true });
  }
};

const handleCancel = () => {
  emit("update:dialogVisibleTransfer", false);
};

// getTableData({
//   pageNum: 1,
//   pageSize: 10000
// });
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;

  .form__footer {
    width: 100%;
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}
.content-table {
  width: 100%;
  height: 100%;
  // border: 1px solid #e4e7ed;
  &--wrap {
    display: flex;
    justify-content: center;
    align-items: flex-start;
    .table-left {
      margin-right: 10px;
      &--header {
        padding: 5px 0;
      }
      &--btn {
        float: right;
      }
      &--footer {
        display: flex;
        justify-content: flex-start;
      }
    }
    .table-right {
      &--header {
        height: 42px;
        padding: 5px 0;
      }
    }
  }
}
.content-table :deep .el-table__fixed-right-patch {
  background: #eef1f6 !important;
}

.content-table :deep .el-table__header {
  background: #eef1f6 !important;
}

.content-table
  :deep
  .el-table__header
  .el-table-column--selection
  .cell
  .el-checkbox {
  display: none;
}
.content-table
  :deep
  .el-table__header
  .el-table-column--selection
  .cell:before {
  content: "选择";
}

.content-table :deep .el-table__header {
  height: 49px;
}
.content-table :deep .el-table__row {
  height: 49px;
}
</style>
